package com.webex.ta.hydra.gui.macro.action;

import com.webex.ta.hydra.gui.action.ActionHandler;
import com.webex.ta.hydra.gui.action.ActionNames;
import com.webex.ta.hydra.gui.action.ActionRouter;
import com.webex.ta.hydra.gui.macro.MacroEditorContext;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-14
 * Time: 15:57:43
 */
public class MacroCloseAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.MACR0_CLOSE);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        performAction(e);
    }

    private static boolean needSaveBeforeClose() {
        MacroEditorContext context = MacroEditorContext.getInstance();
        if (context.getMacroDefFile() != null)
            return true;
        else
            return context.getEditor().getMacroDefinitions().size() > 0;
    }

    static boolean performAction(ActionEvent e) {
        if (needSaveBeforeClose()) {
            int response;
            if ((response = JOptionPane.showConfirmDialog(MacroEditorContext.getInstance().getEditor(),
                    "There are items that have not been saved.  Do you wish to save before closing?",
                    "Save?",
                    JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE)) == JOptionPane.YES_OPTION) {
                ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(), ActionNames.MACR0_SAVE));
            }
            if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.CANCEL_OPTION) {
                return false; // Don't clear the plan
            }
        }

        closeProject(e);
        return true;
    }

    static void closeProject(ActionEvent e) {
		MacroEditorContext context = MacroEditorContext.getInstance();

		// Clear the name of the test plan file
		context.setMacroDefFile(null);
        context.getEditor().reset();
	}
}
